package com.lvbaoins.Harmony.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.lvbaoins.Harmony.core.base.controller.BaseController;
import com.lvbaoins.Harmony.system.common.Strategy;
import com.lvbaoins.Harmony.system.common.factory.ActionFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Controller
@RequestMapping("/downLoadFile")
@Slf4j
public class DownLoadController extends BaseController {

    //@Autowired
    //private FastDFSClient fastDFSClient;


    /**
     * 下载
     *
     * @param orderNo
     */
    @RequestMapping("")
    public void downLoad(String productCode, String orderNo, HttpServletResponse response, HttpServletRequest request) throws IOException {
        try {

            Strategy strategy = ActionFactory.get(productCode);
            strategy.exec(orderNo, response);

        } catch (Exception e) {
            log.info("下载失败！-->" + e);
            response.setHeader("Set-Cookie", "fileDownload=false; path=/");
            JSONObject json =new JSONObject();
            json.put("result"," success");
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = null;
            out = response.getWriter();
            out.write(json.toString());
        }

    }

    /**
     * 批量下载
     * @param arr
     * @param productCode
     * @param request
     * @param response
     */
    @RequestMapping("/downLoadBatch")
    public void downLoadBatch(@RequestParam(value = "arr[]", required = true) Integer[] arr,String productCode, HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {

            Strategy strategy = ActionFactory.get(productCode);
            strategy.downLoadBatch(arr,request,response);

        } catch (Exception e) {
            log.error("下载失败！-->" + e);
            response.setHeader("Set-Cookie", "fileDownload=false; path=/");
            JSONObject json =new JSONObject();
            json.put("result"," success");
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = null;
            out = response.getWriter();
            out.write(json.toString());
        }

    }
}
